import socket
import ssl


def get_baidu():
    host = 'www.baidu.com'
    port = 80

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    sock.connect((host, port))

    request_url = 'GET / HTTP/1.1\r\nHost: ' + host + '\r\n\r\n'

    sock.send(request_url.encode())
    
    rec = sock.recv(1024)

    index = rec.find(b'\r\n\r\n')  
    head = rec[:index]
    body = rec[index+4:]

    headers = head.split(b'\r\n')
    for header in headers:
        if header.startswith(b'Content-Length'):
            content_length = int(header.split(b' ')[1])

    length = len(body)

    while length < content_length:
        rec = sock.recv(1024)
        length += len(rec)
        body += rec

    sock.close()

    headers_str = head.decode()

    print('====== baidu ======')
    print(headers_str)


def get_sogou():
    host = 'www.sogou.com'
    port = 443

    sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))

    sock.connect((host, port))

    request_url = 'GET / HTTP/1.1\r\nHost: ' + host + '\r\nConnection: close\r\n\r\n'

    sock.send(request_url.encode())
    
    response = b''

    rec = sock.recv(1024)
    while rec:
        response += rec
        rec = sock.recv(1024)

    data_str = response.decode()
    ip = data_str.split('window.lead_ip = \'')[1].split('\'')[0]

    print('====== sogou ======')
    print(ip)



def main():
    get_baidu()
    get_sogou()


if __name__ == '__main__':
    main()

